package songgao.papers.iEC;

import java.io.IOException;
import java.io.StringWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

@SuppressWarnings("serial")
public class AdminAJAXHandler extends HttpServlet {
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		resp.getWriter().println("GET works.");
	}
	
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String action = req.getParameter("action");
		if (action == null)
			resp.getWriter().println("action parameter required");
		else if (action.toLowerCase().equals("getstatus")) {
			this.getStatus(req, resp);
		} else if (action.toLowerCase().equals("startnewcomputing")) {
			this.startNewComputing(req, resp);
		}
	}

	private void getStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		try {
			Master master=DataManager.INSTANCE.getMaster();
			resp.getWriter().println("PopulationSize: " + master.getPopulationPool().size());
			resp.getWriter().println("Slave Count: " + master.getSlaves().size());
			resp.getWriter().print("Population Generations: ");
			for(Population pop : master.getPopulationPool()){
				resp.getWriter().print(pop.getGeneration()+", ");
			}
			resp.getWriter().println();
		} catch (Exception ex) {
			resp.getWriter().println(ex);
		}
	}

	private void startNewComputing(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		try {
			Boolean result = Controller.INSTANCE.StartNewComputing();
			resp.setContentType("text/xml");
			DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = db.newDocument();
			Element resultElement = doc.createElement("StartNewComputingResult");
			resultElement.setAttribute("Result", result ? "success" : "failed");
			doc.appendChild(resultElement);

			TransformerFactory transfac = TransformerFactory.newInstance();
			Transformer trans = transfac.newTransformer();

			trans.setOutputProperty(OutputKeys.INDENT, "yes");

			StringWriter sw = new StringWriter();
			DOMSource source = new DOMSource(doc);
			trans.transform(source, new StreamResult(sw));

			resp.getWriter().println(sw.toString());
		} catch (Exception ex) {
			resp.getWriter().println(ex);
		}
	}
}
